<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">

  <!-- PACE Progress Bar START -->
  
  

  <!-- PACE Progress Bar START -->

  
  <title>
    
    python+opencv教程拓展挑战：pyqt编写gui界面 |
    
    ex2tron&#39;s Tech Blog
  </title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="ex2tron,opencv,tensorflow" />
  
  
  
  
  <meta name="description" content="拓展挑战：编写GUI图像处理应用程序。">
<meta name="keywords" content="OpenCV,Python,图像处理,PyQt">
<meta property="og:type" content="article">
<meta property="og:title" content="Python+OpenCV教程拓展挑战：PyQt编写GUI界面">
<meta property="og:url" content="http://ex2tron.wang/opencv-python-using-pyqt5-create-gui/index.html">
<meta property="og:site_name" content="ex2tron&#39;s Tech Blog">
<meta property="og:description" content="拓展挑战：编写GUI图像处理应用程序。">
<meta property="og:locale" content="en">
<meta property="og:image" content="http://pic.ex2tron.top/cv2_pyqt_gui_sample.jpg">
<meta property="og:updated_time" content="2018-12-02T13:37:44.709Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python+OpenCV教程拓展挑战：PyQt编写GUI界面">
<meta name="twitter:description" content="拓展挑战：编写GUI图像处理应用程序。">
<meta name="twitter:image" content="http://pic.ex2tron.top/cv2_pyqt_gui_sample.jpg">
  
  <link rel="alternate" href="/atom.xaml" title="ex2tron&#39;s Tech Blog" type="application/atom+xml">
  
  <link rel="icon" href="/img/bookshelf.ico">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face {
      font-family: futura-pt;
      src: url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");
      font-weight: 500;
      font-style: normal;
    }

    @font-face {
      font-family: futura-pt;
      src: url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");
      font-weight: 500;
      font-style: normal;
    }

    @font-face {
      font-family: futura-pt;
      src: url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");
      font-weight: lighter;
      font-style: normal;
    }

    @font-face {
      font-family: futura-pt;
      src: url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");
      font-weight: 400;
      font-style: italic;
    }
  </style>

  <link rel="stylesheet" id="athemes-headings-fonts-css" href="//fonts.googleapis.com/css?family=Yanone+Kaffeesatz%3A200%2C300%2C400%2C700&amp;ver=4.6.1"
    type="text/css" media="all">
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css">
  <link rel="stylesheet" href="/css/hiero.css">
  <link rel="stylesheet" href="/css/glyphs.css">
  
  <link rel="stylesheet" href="/css/vdonate.css">
  

  <!-- Custom CSS -->
  <link rel="stylesheet" href="/css/my.css">

  <script>
    (function () {
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      }
      else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>

</head>
<script>
var themeMenus = {};

  themeMenus["/"] = "Home"; 

  themeMenus["/archives"] = "Archives"; 

  themeMenus["/categories"] = "Categories"; 

  themeMenus["/tags"] = "Tags"; 

  themeMenus["/about"] = "About"; 

</script>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  <header id="allheader" class="site-header" role="banner">
  <div class="clearfix container">
      <div class="site-branding">

          <h1 class="site-title">
            
              <a href="/" title="ex2tron&#39;s Tech Blog" rel="home"> ex2tron&#39;s Tech Blog </a>
            
          </h1>

          
            
          <nav id="main-navigation" class="main-navigation" role="navigation">
            <a class="nav-open">Menu</a>
            <a class="nav-close">Close</a>
            <div class="clearfix sf-menu">

              <ul id="main-nav" class="nmenu sf-js-enabled">
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/">Home</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/archives">Archives</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/categories">Categories</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/tags">Tags</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/about">About</a> </li>
                    
              </ul>
            </div>
          </nav>


      </div>
  </div>
</header>




  <div id="container">
    <div id="wrap">
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-Python-OpenCV教程挑战任务2：PyQt编写GUI界面" style="width: 66%; float:left;" class="article article-type-post" itemscope itemprop="blogPost" >
  <div id="articleInner" class="clearfix post-1016 post type-post status-publish format-standard has-post-thumbnail hentry category-template-2 category-uncategorized tag-codex tag-edge-case tag-featured-image tag-image tag-template">
    
<div class="article-gallery">
  <div class="article-gallery-photos">
    
      <a class="article-gallery-img fancybox" href="http://pic.ex2tron.top/cv2_pyqt_gui_sample.jpg" rel="gallery_cjxj6dyh200b75w59sm0l897a">
        <img src="http://pic.ex2tron.top/cv2_pyqt_gui_sample.jpg" itemprop="image">
      </a>
    
  </div>
</div>

    
      <header class="article-header">
        
  
    <h1 class="thumb" class="article-title" itemprop="name">
      Python+OpenCV教程拓展挑战：PyQt编写GUI界面
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	Posted on <a href="/opencv-python-using-pyqt5-create-gui/" class="article-date">
	  <time datetime="2017-12-09T09:30:34.000Z" itemprop="datePublished">December 9, 2017</time>
	</a>

      
	<!-- TODO: ex2tron.wang 启用但暂时不显示访问量 2019年3月20日 -->
	<!-- <span id="busuanzi_container_page_pv">
	  本文总阅读量<span id="busuanzi_value_page_pv"></span>次
	</span> -->

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <p>拓展挑战：编写GUI图像处理应用程序。<a id="more"></a></p>
<hr>
<h2 id="挑战内容"><a href="#挑战内容" class="headerlink" title="挑战内容"></a>挑战内容</h2><p>前面我们学习的OpenCV内容都是运行在命令行中的，没有界面，所以本次的拓展挑战内容便是：</p>
<blockquote>
<p><strong>了解Python编写<a href="https://baike.baidu.com/item/GUI" target="_blank" rel="external">GUI</a>界面的方法，使用PyQt5编写如下的图像处理应用程序，实现打开摄像头、捕获图片、读取本地图片、灰度化和Otsu自动阈值分割的功能。</strong></p>
</blockquote>
<p><img src="http://pic.ex2tron.top/cv2_pyqt_gui_sample.jpg" alt=""></p>
<p><strong>挑战题不会做也木有关系，但请务必在自行尝试后，再看下面的解答噢，</strong>不然…我也没办法(￣▽￣)”</p>
<hr>
<h2 id="挑战解答"><a href="#挑战解答" class="headerlink" title="挑战解答"></a>挑战解答</h2><h3 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h3><blockquote>
<p>目前我们学的内容都是跑在命令行中的，并没有界面，那么”脚本语言”Python如何搭建GUI界面呢？</p>
</blockquote>
<p>其实Python支持多种图形界面库，如<a href="https://wiki.python.org/moin/TkInter" target="_blank" rel="external">Tk(Tkinter)</a>、<a href="https://www.wxpython.org/" target="_blank" rel="external">wxPython</a>、<a href="https://wiki.python.org/moin/PyQt" target="_blank" rel="external">PyQt</a>等，虽然Python自带Tkinter，无需额外安装包，但我更推荐使用PyQt，一是因为它完全基于Qt，跨平台，功能强大，有助于了解Qt的语法，二是Qt提供了Designer设计工具，界面设计上可以拖控件搞定，非常方便，大大节省时间。</p>
<ul>
<li>最新版本：PyQt 5.x</li>
<li>官网（可能需要翻墙）：<a href="https://www.riverbankcomputing.com/software/pyqt/" target="_blank" rel="external">https://www.riverbankcomputing.com/software/pyqt/</a></li>
</ul>
<p>大家感兴趣的话，除去官网，下面是一些可参考的资源：</p>
<ul>
<li><a href="https://wiki.python.org/moin/PyQt" target="_blank" rel="external">Python Wiki: PyQt</a></li>
<li><a href="https://wiki.python.org/moin/PyQt/Tutorials" target="_blank" rel="external">PyQt/Tutorials</a></li>
<li>PyQt5 tutorial：<a href="http://zetcode.com/gui/pyqt5/" target="_blank" rel="external">英文原版</a></li>
<li>PyQt4 tutorial：<a href="http://www.qaulau.com/books/PyQt4_Tutorial/index.html" target="_blank" rel="external">中文版</a>、<a href="http://zetcode.com/gui/pyqt4/" target="_blank" rel="external">英文原版</a></li>
<li><a href="https://doc.qt.io/qt-5/" target="_blank" rel="external">Qt5 Documentation</a></li>
<li>中文参考书：<a href="https://www.amazon.cn/dp/B075VWFYFH/ref=sr_1_1?ie=UTF8&amp;qid=1543407852&amp;sr=8-1&amp;keywords=PyQt5%E5%BF%AB%E9%80%9F%E5%BC%80%E5%8F%91%E4%B8%8E%E5%AE%9E%E6%88%98" target="_blank" rel="external">PyQt5快速开发与实战</a></li>
<li><a href="http://eric-ide.python-projects.org/" target="_blank" rel="external">基于Qt的Python IDE Eric</a></li>
</ul>
<h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">pip install pyqt5</div></pre></td></tr></table></figure>
<p>下载速度慢的话，可以到<a href="https://pypi.org/project/PyQt5/#files" target="_blank" rel="external">PyPI</a>上下载离线版安装。另外我推荐使用Qt Designer来设计界面，如果你装的是Anaconda的话，就已经自带了designer.exe，例如我的是在：D:\ProgramData\Anaconda3\Library\bin\，如果是普通的Python环境，则需要自行安装：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">pip install pyqt5-tools</div></pre></td></tr></table></figure>
<p>安装完成后，designer.exe应该在Python安装目录下：xxx\Lib\site-packages\pyqt5_tools\。</p>
<p>可以使用下面的代码生成一个简单的界面：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> sys</div><div class="line"><span class="keyword">from</span> PyQt5.QtWidgets <span class="keyword">import</span> QApplication, QWidget</div><div class="line"></div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</div><div class="line">    app = QApplication(sys.argv)</div><div class="line"></div><div class="line">    window = QWidget()</div><div class="line">    window.setWindowTitle(<span class="string">'Hello World!'</span>)</div><div class="line">    window.show()</div><div class="line"></div><div class="line">    sys.exit(app.exec_())</div></pre></td></tr></table></figure>
<p><img src="http://pic.ex2tron.top/cv2_pyqt5_hello_world_sample.jpg" alt=""></p>
<h3 id="界面设计"><a href="#界面设计" class="headerlink" title="界面设计"></a>界面设计</h3><p>根据我们的挑战内容，解决思路是使用Qt Designer来设计界面，使用Python完成代码逻辑。打开designer.exe，会弹出创建新窗体的窗口，我们直接点击“create”：</p>
<p><img src="http://pic.ex2tron.top/cv2_pyqt5_designer_main_ui.jpg" alt=""></p>
<p>界面的左侧是Qt的常用控件”Widget Box”，右侧有一个控件属性窗口”Property Editor”，其余暂时用不到。本例中我们只用到了”Push Button”控件和”Label”控件：最上面的三个Label控件用于显示图片，可以在属性窗口调整它的大小，我们统一调整到150×150：</p>
<p><img src="http://pic.ex2tron.top/cv2_pyqt5_main_ui_rough.jpg" alt=""></p>
<p><img src="http://pic.ex2tron.top/cv2_pyqt5_designer_property_windows.jpg" alt=""></p>
<p>另外，控件上显示的文字”text”属性和控件的名字”objectName”属性需要修改，便于显示和代码调用。可以按照下面我推荐的命名：</p>
<table>
<thead>
<tr>
<th style="text-align:center">控件</th>
<th style="text-align:center">显示内容text</th>
<th style="text-align:center">控件名objectName</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">PushButton</td>
<td style="text-align:center">打开摄像头</td>
<td style="text-align:center">btnOpenCamera</td>
</tr>
<tr>
<td style="text-align:center">PushButton</td>
<td style="text-align:center">捕获图片</td>
<td style="text-align:center">btnCapture</td>
</tr>
<tr>
<td style="text-align:center">PushButton</td>
<td style="text-align:center">打开图片</td>
<td style="text-align:center">btnReadImage</td>
</tr>
<tr>
<td style="text-align:center">PushButton</td>
<td style="text-align:center">灰度化</td>
<td style="text-align:center">btnGray</td>
</tr>
<tr>
<td style="text-align:center">PushButton</td>
<td style="text-align:center">阈值分割(Otsu)</td>
<td style="text-align:center">btnThreshold</td>
</tr>
<tr>
<td style="text-align:center">Label</td>
<td style="text-align:center">摄像头</td>
<td style="text-align:center">labelCamera</td>
</tr>
<tr>
<td style="text-align:center">Label</td>
<td style="text-align:center">捕获图</td>
<td style="text-align:center">labelCapture</td>
</tr>
<tr>
<td style="text-align:center">Label</td>
<td style="text-align:center">结果图</td>
<td style="text-align:center">labelResult</td>
</tr>
</tbody>
</table>
<p>这样大致界面就出来了，很简单：</p>
<p><img src="http://pic.ex2tron.top/cv2_pyqt5_main_ui_word.jpg" alt=""></p>
<h3 id="按钮事件"><a href="#按钮事件" class="headerlink" title="按钮事件"></a>按钮事件</h3><p>如果你之前有过一些GUI开发经验，比如MFC，WinForm等，就知道GUI是通过事件驱动的，什么意思呢？比如前面我们已经设计好了界面，接下来就需要实现”打开摄像头”到”阈值分割”这5个按钮的功能，也就是给每个按钮指定一个”函数”，逻辑代码写在这个函数里面。这种函数就称为事件，Qt中称为槽连接。</p>
<p>点击Designer工具栏的”Edit Signals/Slots”按钮，进入槽函数编辑界面，点击旁边的”Edit Widgets”可以恢复正常视图：</p>
<p><img src="http://pic.ex2tron.top/cv2_pyqt5_designer_edit_singals_slots.jpg" alt=""></p>
<p>然后点击按钮并拖动，当产生类似于电路中的接地符号时释放鼠标，参看下面动图：</p>
<p><img src="http://pic.ex2tron.top/cv2_pyqt5_how_to_create_slots.gif" alt=""></p>
<p>在弹出的配置窗口中，可以看到左侧是按钮的常用事件，我们选择点击事件”clicked()”，然后添加一个名为”btnOpenCamera_Clicked()”的槽函数：</p>
<p><img src="http://pic.ex2tron.top/cv2_pyqt5_how_to_create_slots2.gif" alt=""></p>
<p>重复上面的步骤，给五个按钮添加五个槽函数，最终结果如下：</p>
<p><img src="http://pic.ex2tron.top/cv2_pyqt5_main_click_event.jpg" alt=""></p>
<p>到此，我们就完成了界面设计的所有工作，按下Ctrl+S保存当前窗口为.ui文件。.ui文件其实是按照XML格式标记的内容，可以用文本编辑器将.ui文件打开看看。</p>
<h3 id="ui文件转py代码"><a href="#ui文件转py代码" class="headerlink" title="ui文件转py代码"></a>ui文件转py代码</h3><p>因为我们是用Designer工具设计出的界面，并不是用Python代码敲出来的，所以要想真正运行，需要使用pyuic5将ui文件转成py文件。pyuic5.exe默认在%\Scripts\下，比如我的是在：D:\ProgramData\Anaconda3\Scripts\。</p>
<p>打开cmd命令行，切换到ui文件的保存目录。Windows下有个小技巧，可以在目录的地址栏输入cmd，一步切换到当前目录：</p>
<p><img src="http://pic.ex2tron.top/cv2_pyqt5_pyuic_quick_cmd.gif" alt=""></p>
<p>然后执行这条指令：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">pyuic5 -o mainForm.py using_pyqt_create_ui.ui</div></pre></td></tr></table></figure>
<p>如果出现pyuic5不是内部命令的错误，说明pyuic5的路径没有在环境变量里，添加下就好了。执行正常的话，就会生成mainForm.py文件，里面应该包含一个名为”Ui_MainWindow”的类。</p>
<h3 id="编写逻辑代码"><a href="#编写逻辑代码" class="headerlink" title="编写逻辑代码"></a>编写逻辑代码</h3><blockquote>
<p>经验之谈：mainForm.py文件是根据ui文件生成的，也就是说<strong>重新生成会覆盖掉</strong>。所以为了使界面与逻辑分离，我们需要新建一个逻辑文件。</p>
</blockquote>
<p>在同一工作目录下新建一个”mainEntry.py”的文件，存放逻辑代码。代码中的每部分我都写得比较独立，没有封装成函数，便于理解。代码看上去很长，但很简单，可以每个模块单独看，有几个需要注意的地方我做了注释：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> sys</div><div class="line"><span class="keyword">import</span> cv2</div><div class="line"></div><div class="line"><span class="keyword">from</span> PyQt5 <span class="keyword">import</span> QtCore, QtGui, QtWidgets</div><div class="line"><span class="keyword">from</span> PyQt5.QtCore <span class="keyword">import</span> *</div><div class="line"><span class="keyword">from</span> PyQt5.QtGui <span class="keyword">import</span> *</div><div class="line"><span class="keyword">from</span> PyQt5.QtWidgets <span class="keyword">import</span> QFileDialog, QMainWindow</div><div class="line"></div><div class="line"><span class="keyword">from</span> mainForm <span class="keyword">import</span> Ui_MainWindow</div><div class="line"></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">PyQtMainEntry</span><span class="params">(QMainWindow, Ui_MainWindow)</span>:</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self)</span>:</span></div><div class="line">        super().__init__()</div><div class="line">        self.setupUi(self)</div><div class="line"></div><div class="line">        self.camera = cv2.VideoCapture(<span class="number">0</span>)</div><div class="line">        self.is_camera_opened = <span class="keyword">False</span>  <span class="comment"># 摄像头有没有打开标记</span></div><div class="line"></div><div class="line">        <span class="comment"># 定时器：30ms捕获一帧</span></div><div class="line">        self._timer = QtCore.QTimer(self)</div><div class="line">        self._timer.timeout.connect(self._queryFrame)</div><div class="line">        self._timer.setInterval(<span class="number">30</span>)</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">btnOpenCamera_Clicked</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="string">'''</span></div><div class="line"><span class="string">        打开和关闭摄像头</span></div><div class="line"><span class="string">        '''</span></div><div class="line">        self.is_camera_opened = ~self.is_camera_opened</div><div class="line">        <span class="keyword">if</span> self.is_camera_opened:</div><div class="line">            self.btnOpenCamera.setText(<span class="string">"关闭摄像头"</span>)</div><div class="line">            self._timer.start()</div><div class="line">        <span class="keyword">else</span>:</div><div class="line">            self.btnOpenCamera.setText(<span class="string">"打开摄像头"</span>)</div><div class="line">            self._timer.stop()</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">btnCapture_Clicked</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="string">'''</span></div><div class="line"><span class="string">        捕获图片</span></div><div class="line"><span class="string">        '''</span></div><div class="line">        <span class="comment"># 摄像头未打开，不执行任何操作</span></div><div class="line">        <span class="keyword">if</span> <span class="keyword">not</span> self.is_camera_opened:</div><div class="line">            <span class="keyword">return</span></div><div class="line"></div><div class="line">        self.captured = self.frame</div><div class="line"></div><div class="line">        <span class="comment"># 后面这几行代码几乎都一样，可以尝试封装成一个函数</span></div><div class="line">        rows, cols, channels = self.captured.shape</div><div class="line">        bytesPerLine = channels * cols</div><div class="line">        <span class="comment"># Qt显示图片时，需要先转换成QImgage类型</span></div><div class="line">        QImg = QImage(self.captured.data, cols, rows, bytesPerLine, QImage.Format_RGB888)</div><div class="line">        self.labelCapture.setPixmap(QPixmap.fromImage(QImg).scaled(</div><div class="line">            self.labelCapture.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">btnReadImage_Clicked</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="string">'''</span></div><div class="line"><span class="string">        从本地读取图片</span></div><div class="line"><span class="string">        '''</span></div><div class="line">        <span class="comment"># 打开文件选取对话框</span></div><div class="line">        filename,  _ = QFileDialog.getOpenFileName(self, <span class="string">'打开图片'</span>)</div><div class="line">        <span class="keyword">if</span> filename:</div><div class="line">            self.captured = cv2.imread(str(filename))</div><div class="line">            <span class="comment"># OpenCV图像以BGR通道存储，显示时需要从BGR转到RGB</span></div><div class="line">            self.captured = cv2.cvtColor(self.captured, cv2.COLOR_BGR2RGB)</div><div class="line"></div><div class="line">            rows, cols, channels = self.captured.shape</div><div class="line">            bytesPerLine = channels * cols</div><div class="line">            QImg = QImage(self.captured.data, cols, rows, bytesPerLine, QImage.Format_RGB888)</div><div class="line">            self.labelCapture.setPixmap(QPixmap.fromImage(QImg).scaled(</div><div class="line">                self.labelCapture.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">btnGray_Clicked</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="string">'''</span></div><div class="line"><span class="string">        灰度化</span></div><div class="line"><span class="string">        '''</span></div><div class="line">        <span class="comment"># 如果没有捕获图片，则不执行操作</span></div><div class="line">        <span class="keyword">if</span> <span class="keyword">not</span> hasattr(self, <span class="string">"captured"</span>):</div><div class="line">            <span class="keyword">return</span></div><div class="line"></div><div class="line">        self.cpatured = cv2.cvtColor(self.captured, cv2.COLOR_RGB2GRAY)</div><div class="line"></div><div class="line">        rows, columns = self.cpatured.shape</div><div class="line">        bytesPerLine = columns</div><div class="line">        <span class="comment"># 灰度图是单通道，所以需要用Format_Indexed8</span></div><div class="line">        QImg = QImage(self.cpatured.data, columns, rows, bytesPerLine, QImage.Format_Indexed8)</div><div class="line">        self.labelResult.setPixmap(QPixmap.fromImage(QImg).scaled(</div><div class="line">            self.labelResult.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">btnThreshold_Clicked</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="string">'''</span></div><div class="line"><span class="string">        Otsu自动阈值分割</span></div><div class="line"><span class="string">        '''</span></div><div class="line">        <span class="keyword">if</span> <span class="keyword">not</span> hasattr(self, <span class="string">"captured"</span>):</div><div class="line">            <span class="keyword">return</span></div><div class="line"></div><div class="line">        _, self.cpatured = cv2.threshold(</div><div class="line">            self.cpatured, <span class="number">0</span>, <span class="number">255</span>, cv2.THRESH_BINARY + cv2.THRESH_OTSU)</div><div class="line"></div><div class="line">        rows, columns = self.cpatured.shape</div><div class="line">        bytesPerLine = columns</div><div class="line">        <span class="comment"># 阈值分割图也是单通道，也需要用Format_Indexed8</span></div><div class="line">        QImg = QImage(self.cpatured.data, columns, rows, bytesPerLine, QImage.Format_Indexed8)</div><div class="line">        self.labelResult.setPixmap(QPixmap.fromImage(QImg).scaled(</div><div class="line">            self.labelResult.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))</div><div class="line"></div><div class="line"><span class="meta">    @QtCore.pyqtSlot()</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_queryFrame</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="string">'''</span></div><div class="line"><span class="string">        循环捕获图片</span></div><div class="line"><span class="string">        '''</span></div><div class="line">        ret, self.frame = self.camera.read()</div><div class="line"></div><div class="line">        img_rows, img_cols, channels = self.frame.shape</div><div class="line">        bytesPerLine = channels * img_cols</div><div class="line"></div><div class="line">        cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB, self.frame)</div><div class="line">        QImg = QImage(self.frame.data, img_cols, img_rows, bytesPerLine, QImage.Format_RGB888)</div><div class="line">        self.labelCamera.setPixmap(QPixmap.fromImage(QImg).scaled(</div><div class="line">            self.labelCamera.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))</div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">"__main__"</span>:</div><div class="line">    app = QtWidgets.QApplication(sys.argv)</div><div class="line">    window = PyQtMainEntry()</div><div class="line">    window.show()</div><div class="line">    sys.exit(app.exec_())</div></pre></td></tr></table></figure>
<p><img src="http://pic.ex2tron.top/cv2_pyqt_gui_sample2.jpg" alt=""></p>
<p>本文只是抛砖引玉，介绍了PyQt5的简单使用，想要深入学习，可以参考本文开头的参考资料噢(●ˇ∀ˇ●)</p>
<h2 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h2><ul>
<li><a href="https://github.com/ex2tron/OpenCV-Python-Tutorial/tree/master/%E6%8C%91%E6%88%98%E4%BB%BB%E5%8A%A12%EF%BC%9APyQt5%E7%BC%96%E5%86%99GUI%E7%95%8C%E9%9D%A2" target="_blank" rel="external">本节源码</a></li>
</ul>

      
    </div>
    <footer class="entry-meta entry-footer">
      
	<span class="ico-folder"></span>
    <a class="article-category-link" href="/categories/机器视觉/">机器视觉</a>

      
  <span class="ico-tags"></span>
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/OpenCV/">OpenCV</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/PyQt/">PyQt</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Python/">Python</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/图像处理/">图像处理</a></li></ul>


      <div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a></div>
      <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","weixin"],"viewText":"分享到：","viewSize":"16"},"selectShare":{"bdContainerClass":null,"bdSelectMiniList":["qzone","tsina","weixin"]}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>

      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
  <script>
    var a = new Donate({
      title: '谢谢支持，我会更加✊~', // 可选参数，打赏标题
      // btnText: 'Donate', // 可选参数，打赏按钮文字
      btnText: '赏', // 可选参数，打赏按钮文字
      el: document.getElementById('donation_div'),
      wechatImage: '/img/wechat.jpg',
      alipayImage: '/img/alipay.jpg'
    });
  </script>
      
                  
      
        
	<div id="comment">
		<!-- 来必力City版安装代码 -->
		<div id="lv-container" data-id="city" data-uid="MTAyMC8yOTQ4MS82MDQ5">
		<script type="text/javascript">
		   (function(d, s) {
		       var j, e = d.getElementsByTagName(s)[0];

		       if (typeof LivereTower === 'function') { return; }

		       j = d.createElement(s);
		       j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
		       j.async = true;

		       e.parentNode.insertBefore(j, e);
		   })(document, 'script');
		</script>
		<noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
		</div>
		<!-- City版安装代码已完成 -->
	</div>


      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/opencv-python-extra-contrast-brightness/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          Python+OpenCV教程番外篇7：亮度与对比度
        
      </div>
    </a>
  
  
    <a href="/opencv-python-clock-drawing/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">Python+OpenCV教程挑战任务：画动态时钟</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">Contents</strong>
    
      <ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#挑战内容"><span class="nav-number">1.</span> <span class="nav-text">挑战内容</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#挑战解答"><span class="nav-number">2.</span> <span class="nav-text">挑战解答</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#简介"><span class="nav-number">2.1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#安装"><span class="nav-number">2.2.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#界面设计"><span class="nav-number">2.3.</span> <span class="nav-text">界面设计</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#按钮事件"><span class="nav-number">2.4.</span> <span class="nav-text">按钮事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ui文件转py代码"><span class="nav-number">2.5.</span> <span class="nav-text">ui文件转py代码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编写逻辑代码"><span class="nav-number">2.6.</span> <span class="nav-text">编写逻辑代码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#引用"><span class="nav-number">3.</span> <span class="nav-text">引用</span></a></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      <footer id="footer" class="site-footer">
  

        <div class="clearfix container">
          <div class="site-info">
            &copy;
            <!-- 2019
              ex2tron&#39;s Tech Blog All Rights Reserved. -->
              Made by ex2tron | 2019
                <!-- TODO: ex2tron.wang 启用但暂时不显示访问量 2019年3月20日 -->
                <!--  -->
                  <!-- <span id="busuanzi_container_site_uv">
                    本站访客数
                    <span id="busuanzi_value_site_uv"></span>人次 本站总访问量
                    <span id="busuanzi_value_site_pv"></span>次
                  </span> -->
                  <!--  -->
          </div>
          <!-- <div class="site-credit">
            Theme by
              <a href="https://github.com/iTimeTraveler/hexo-theme-hiero" target="_blank">hiero</a>
          </div> -->
          <div>
            <p>&nbsp | 电影台词分享：
              <a href="http://moviequotes.ex2tron.wang/" style="font-weight: bold">MovieQuotes</a>
            </p>
          </div>
        </div>
</footer>


<!-- min height -->

<script>
  var contentdiv = document.getElementById("content");

  contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("allheader").offsetHeight - document.getElementById("footer").offsetHeight + "px";
</script>

<!-- Custome JS -->
<script src="/js/my.js"></script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="/js/main.js"></script>







  <div style="display: none;">
    <script src="https://s95.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>
  </div>



	<!-- <script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"> -->
	<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js" async=""></script>
</body>
</html>
